import Vue from 'vue'
import App from './App.vue'
import router from './router'

//创建全局前置路由守卫
//拦截所有的路由跳转,进行校验
//只有校验了才能通过
router.beforeEach((to , from , next )=>{
  // console.log(to);
  // console.log(from);
  // console.log(next);
   if(to.path == '/user'){
      if(localStorage.getItem('token')){
        next();
      }else{
        router.replace('/login')
      }
   }else{
      next()
   }
})



import Vant from 'vant'
import 'vant/lib/index.css';

import Axios from 'axios'

import { Toast } from 'vant';

Axios.defaults.baseURL = 'http://127.0.0.1:3000';

// 拦截响应内容
Axios.interceptors.response.use((res)=>{
  // console.log(res);
   const {message, statusCode} = res.data
   
   if(statusCode == 401){
      //  console.log(message);
      Toast.fail(message);
      router.replace('/login')
   }
  return res
})

// 拦截请求内容
Axios.interceptors.request.use((req)=>{
  // console.log(req);
  if(localStorage.getItem('token') && !req.headers.Authorization){
    req.headers.Authorization = "Bearer "+localStorage.getItem('token')
  }
   
  return req
})

//绑定到vue的原型里去
Vue.prototype.$axios = Axios

Vue.use(Vant);


Vue.config.productionTip = false

new Vue({
  router,
  render: function (h) { return h(App) }
}).$mount('#app')
